package elearning.service;

import java.util.List;
import java.util.Map;

import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

import elearning.meta.ExamMeta;
import elearning.meta.OptionMeta;
import elearning.meta.QuestionMeta;
import elearning.model.Exam;
import elearning.model.Option;
import elearning.model.Question;

public class ElearningService {
	private ExamMeta e = new ExamMeta();
	private QuestionMeta q = new QuestionMeta();
	private OptionMeta o = new OptionMeta();

	public Exam get(Key key, Long version) {
		return Datastore.get(e, key, version);
	}

	public List<Exam> getAll() {
		return Datastore.query(e).asList();
	}

	public List<Question> getQuestionAll() {
		return Datastore.query(q).asList();
	}

	public List<Question> getQuestionByExam(Key examKey) {
		return Datastore.query(q, examKey).asList();
	}

	public void insert(Exam exam) {
		Transaction tx = Datastore.beginTransaction();
		Datastore.put(tx, exam);
		Datastore.commit(tx);
	}

	public Exam update(Key key, Long version, Map<String, Object> input) {
		Transaction tx = Datastore.beginTransaction();
		Exam exam = Datastore.get(tx, e, key, version);
		BeanUtil.copy(input, exam);
		Datastore.put(tx, exam);
		Datastore.commit(tx);
		return exam;
	}

	public void delete(Key key, Long version) {
		Transaction tx = Datastore.beginTransaction();
		Exam exam = Datastore.get(tx, e, key, version);
		Datastore.delete(tx, exam.getKey());
		Datastore.commit(tx);
	}

	public void insertEG(List<Object> models) {
		Transaction tx = Datastore.beginTransaction();
		Datastore.put(tx, models);
		Datastore.commit(tx);
	}

	public Question getQuestion(Key key, Long version) {
		return Datastore.get(q, key, version);
	}

	public List<Option> getOptionByQuestion(Key questionKey) {
		return Datastore.query(o, questionKey).asList();
	}

	public void deleteQuestion(Key key, Long version) {
		Transaction tx = Datastore.beginTransaction();
		Question question = Datastore.get(tx, q, key, version);
		Datastore.delete(tx, question.getKey());
		Datastore.commit(tx);
	}

	public void deleteOptionByQuestion(Question question) {
		Transaction tx = Datastore.beginTransaction();
		List<Option> optionList = getOptionByQuestion(question.getKey());
		for (Option option : optionList) {
			Datastore.delete(tx, option.getKey());
		}
		Datastore.commit(tx);
	}
}
